# -*- coding: utf-8 -*-
import sys
import json
from xml.dom.minidom import parse


# 读取节点中的 counter 内容
def read_counter(node) -> dict:
    json = {}
    counterNodes = node.getElementsByTagName("counter")
    for i in range(len(counterNodes)):
        counterNode = counterNodes[i]
        type = counterNode.getAttribute("type")
        missed = int(counterNode.getAttribute("missed"))
        covered = int(counterNode.getAttribute("covered"))
        if type == "CLASS":
            json["class"] = {"total": missed + covered, "covered": covered}
        elif type == "METHOD":
            json["method"] = {"total": missed + covered, "covered": covered}
        elif type == "LINE":
            json["line"] = {"total": missed + covered, "covered": covered}

    return json


# 解析单测覆盖率报告，xml文件
# @param path xml文件绝对路径
def read_coverage_report(path: str, name: str = "") -> dict:
    # Document Object Model
    dom = parse(path)

    rootNode = dom.documentElement
    json = read_counter(rootNode)
    json["name"] = rootNode.getAttribute("name")
    # 优先使用外部内容，指定报告的名称
    if len(name) >0:
        json["name"] = name

    # 汇总信息解析出来
    packageNodes = rootNode.getElementsByTagName("package")

    json["packages"] = []
    for i in range(len(packageNodes)):
        packageNode = packageNodes[i]
        packageName = packageNode.getAttribute("name")

        package = read_counter(packageNode)
        package["name"] = packageName

        sourcefiles = []  # 所有资源文件
        package["sourcefiles"] = sourcefiles
        sourcefileClasses = {}
        sourcefileNodes = packageNode.getElementsByTagName("sourcefile")
        for j in range(len(sourcefileNodes)):
            sourcefileNode = sourcefileNodes[j]
            sourcefilename = sourcefileNode.getAttribute("name")
            # 只有一个 line 信息
            sourcefile = read_counter(sourcefileNode)
            sourcefile["name"] = sourcefilename
            sourcefileClasses[sourcefilename] = []
            sourcefiles.append(sourcefile)

        # 给 sourcefile 补充 class + method 信息
        classNodes = packageNode.getElementsByTagName("class")
        for k in range(len(classNodes)):
            classNode = classNodes[k]
            sourcefilename = classNode.getAttribute("sourcefilename")
            clazz = read_counter(classNode)
            sourcefileClasses[sourcefilename].append(clazz)

        for h in range(len(sourcefiles)):
            sourcefile = sourcefiles[h]
            name = sourcefile["name"]
            classes = sourcefileClasses[name]

            # 这个资源文件中有多少个类
            classTotal = len(classes)
            classCovered = 0
            methodTotal = 0
            methodCovered = 0
            for m in range(classTotal):
                method = classes[m]["method"]
                # 类中有一个方法被覆盖，该类就被覆盖
                if method["covered"] > 0:
                    classCovered += 1
                # 记录方法总数
                methodTotal += method["total"]
                methodCovered += method["covered"]

            sourcefile["class"] = {"total": classTotal, "covered": classCovered}
            sourcefile["method"] = {"total": methodTotal, "covered": methodCovered}

        json["packages"].append(package)

    return json


# def main() -> int:
#     json_obj = read_report(
#         r"D:\workspace01\Android-APT\UnitTestCoverageDemo\app\build\reports\kover\reportRelease.xml"
#     )
#     print(json.dumps(json_obj))
#     return 0


# # main函数入口
# if __name__ == "__main__":
#     sys_ret = main()
#     sys.exit(sys_ret)
